package models

import (
	"errmsg"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"time"
	"tools"
)

type EquipmentLog struct {
	Id         string `orm:"column(id);pk" json:"id" form:"id"`
	UserId     string `orm:"column(user_id)" json:"user_id" form:"user_id"`
	Sta        string `orm:"column(sta)" json:"sta" form:"sta"`
	Status     int    `orm:"column(status)" json:"status" form:"status"`
	CreateTime int64  `orm:"column(create_time)" json:"create_time" form:"create_time"`
}

func (m *EquipmentLog) TableName() string {
	return "equipment_log"
}

func init() {
	orm.RegisterModel(new(EquipmentLog))
}

func NewEquipmentLog() *EquipmentLog {
	return &EquipmentLog{}
}

func GetAllEquipmentLogBySta(sta string, page int) ([]*EquipmentLog, error) {
	var (
		lists []*EquipmentLog
		err   error
		qs    orm.QuerySeter
		count int64
	)

	lists = []*EquipmentLog{}
	qs = orm.NewOrm().QueryTable(NewEquipmentLog().TableName()).Filter("sta", sta).OrderBy("-create_time")

	if page > 0 {
		row := beego.AppConfig.DefaultInt("page_limit", 20)
		start := (page - 1) * row
		qs = qs.Limit(row).Offset(start)
	}

	if count, err = qs.All(&lists); err != nil {
		logs.Error(err)
		return nil, err
	}
	if count == 0 {
		return nil, nil
	}

	return lists, nil
}

func ClearEquipmentLogBySta(sta string) error {
	_, err := orm.NewOrm().QueryTable(NewEquipmentLog().TableName()).Filter("sta", sta).Delete()
	return err
}

func AddEquipmentLog(sta string, act int) error {
	log := &EquipmentLog{
		Id:         tools.GUUID(),
		Sta:        sta,
		Status:     act,
		CreateTime: time.Now().Unix(),
	}

	if _, err := orm.NewOrm().Insert(log); err != nil {
		logs.Error("AddEquipmentLog error:", err)
		return errmsg.ErrResponseFail
	}

	return nil
}
